package com.sangeng.service.impl;

import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.entity.LoginUser;
import com.sangeng.domain.entity.User;
import com.sangeng.domain.vo.BlogUserLoginVo;
import com.sangeng.domain.vo.UserInfoVo;
import com.sangeng.service.BlogLoginService;
import com.sangeng.utils.BeanCopyUtils;
import com.sangeng.utils.JwtUtil;
import com.sangeng.utils.RedisCache;
import org.apache.http.auth.AUTH;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Objects;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    //自动装配authenticationManager
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(User user) {
       //1.调用authenticationManager的authenticate方法进行认证
        UsernamePasswordAuthenticationToken authenticationToken
                =new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //2.查看authenticate是否为空
        if(Objects.isNull(authenticate)){
            //为空抛出异常
            throw new RuntimeException("用户名或密码错误");
        }
        //3.获取封装的用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //4.通过工具类生成jwt
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //5.将用户信息存入redis中
        redisCache.setCacheObject("bloglogin:"+userId,loginUser);
        //6.将结果进行封装
        //6.1对userInfo进行属性赋值
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser, UserInfoVo.class);
        return ResponseResult.okResult(new BlogUserLoginVo(jwt,userInfoVo));
    }
    /**
     * 用户退出
     * @return
     */
    @Override
    public ResponseResult logout() {
        //1.从SecurityContextHolder获取当前用户的所有信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //2.获取当前用户的消息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        //3.从redis中删除当前用户的消息
        redisCache.deleteObject("bloglogin:"+userId);
        return ResponseResult.okResult();
    }
}
